package com.sy.server.privilege.aspect;

import com.sy.server.util.MyConst;
import com.sy.server.dao.RedisDAO;
import com.sy.server.privilege.anno.Permission;
import com.sy.server.util.IpUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Set;

@Aspect
@Component("userAspect")
public class PrivilegeAspect {
    @Autowired
    private RedisDAO rdao;
    @Autowired
    private HttpServletRequest request;

    private Logger logger=LoggerFactory.getLogger(PrivilegeAspect.class);

    @Pointcut("execution(* com.sy.server.controller..*.*(..))")
    public void userAspect(){}

    @Around("userAspect()")
    public Object verifyStatus(ProceedingJoinPoint joinPoint) throws Throwable{
        Class clazz=joinPoint.getTarget().getClass();
        if(!clazz.isAnnotationPresent(Permission.class)){
            return joinPoint.proceed();
        }
        Method method=((MethodSignature)joinPoint.getSignature()).getMethod();
        if(!method.isAnnotationPresent(Permission.class)){
            return joinPoint.proceed();
        }
        String curIp= IpUtil.getIpAddress(request);

        Set set=rdao.keys(curIp+"*"+ MyConst.LOCK_SUFFIX);
        //set不空，表示当前机器有用户登录，可以执行后续方法，反之跳到登录界面
        if(!set.isEmpty()){
            logger.info("权限验证成功，执行方法[{}]",method.getName());
            return joinPoint.proceed();
        }
        logger.error("没有权限，转到登录...");
        return new ResponseEntity<Void>(HttpStatus.FORBIDDEN);
    }
}
